<template>
  <view class="device-query-container">
    <view class="header">
      <view class="header-left">
        <text class="back-btn" @tap="goBack">←</text>
      </view>
      <view class="header-center">
        <text class="title">设备数据查询</text>
      </view>
      <view class="header-right"></view>
    </view>
    
    <view class="search-section">
      <view class="search-container">
        <input 
          type="text" 
          placeholder="请输入设备标识" 
          v-model="searchDeviceId" 
          class="search-input"
        />
        <button class="search-btn" @tap="searchDeviceData">查询</button>
      </view>
      
      <!-- 筛选条件 -->
      <view class="filter-section">
        <view class="filter-item" :class="{ active: currentFilter === 'all' }" @tap="changeFilter('all')">
          全部
        </view>
        <view class="filter-item" :class="{ active: currentFilter === 'analog' }" @tap="changeFilter('analog')">
          遥测
        </view>
        <view class="filter-item" :class="{ active: currentFilter === 'discrete' }" @tap="changeFilter('discrete')">
          遥信
        </view>
        <view class="filter-item" :class="{ active: currentFilter === 'other' }" @tap="changeFilter('other')">
          其他
        </view>
      </view>
    </view>
    
    <view class="result-section">
      <scroll-view class="result-scroll" scroll-y>
        <view class="result-list">
          <view 
            class="result-item" 
            v-for="(item, index) in searchResults" 
            :key="index"
            @tap="showDetail(item)"
          >
            <view class="item-header">
              <text class="device-id">{{ item.deviceIdentifier }}</text>
              <text 
                class="status-tag" 
                :class="{ online: isDeviceOnline(item.updateTime), offline: !isDeviceOnline(item.updateTime) }"
              >
                {{ isDeviceOnline(item.updateTime) ? '在线' : '离线' }}
              </text>
            </view>
            <view class="item-content">
              <text class="service-id">服务类型: {{ getServiceTypeName(item.serviceId) }}</text>
              <text class="update-time">更新时间: {{ formatDateTime(item.updateTime) }}</text>
            </view>
          </view>
          <view v-if="searchResults.length === 0 && searchPerformed" class="no-data">
            暂无数据/No Data
          </view>
          <view v-if="loading" class="loading-text">加载中.../Loading...</view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 分页控件 -->
    <view class="pagination-section" v-if="total > 0">
      <view class="pagination-info">
        共 {{ total }} 条，第 {{ currentPage }} / {{ totalPages }} 页
  
      </view>
      <view class="pagination-controls">
        <button 
          class="page-btn" 
          :disabled="currentPage === 1" 
          @tap="goToPage(currentPage - 1)"
        >
          上一页
        </button>
        <button 
          class="page-btn" 
          :disabled="currentPage === totalPages" 
          @tap="goToPage(currentPage + 1)"
        >
          下一页
        </button>
      </view>
    </view>
    
    <!-- 详情弹窗 -->
    <view class="modal-mask" v-if="showDetailModal" @tap="showDetailModal = false">
      <view class="modal-content" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">详细数据/Data Details</text>
          <text class="modal-close" @tap="showDetailModal = false">×</text>
        </view>
        <view class="modal-body">
          <scroll-view class="detail-scroll" scroll-y>
            <text class="detail-text">{{ formatJsonData(currentDetailData) }}</text>
          </scroll-view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import config from '../../config/index.js'

export default {
  data() {
    return {
      searchDeviceId: '',
      searchResults: [],
      searchPerformed: false,
      showDetailModal: false,
      currentDetailData: '',
      
      // 分页相关
      currentPage: 1,
      pageSize: 20,
      total: 0,
      totalPages: 0,
      loading: false,
      
      // 筛选相关
      currentFilter: 'all', // all, analog, discrete, other
    };
  },
  
  onLoad(options) {
    // 页面加载时可以接收参数
    if (options.deviceId) {
      this.searchDeviceId = options.deviceId;
      this.searchDeviceData();
    }
  },
  
  methods: {
    // 返回登录页
    goBack() {
      uni.navigateBack({
        delta: 1
      });
    },
    
    // 改变筛选条件
    changeFilter(filterType) {
      this.currentFilter = filterType;
      this.currentPage = 1;
      this.searchResults = [];
      this.total = 0;
      this.totalPages = 0;
      this.searchDeviceData();
    },
    
    // 获取服务类型名称（中英文）
    getServiceTypeName(serviceId) {
      switch(serviceId) {
        case 'analog':
          return '遥测/analog';
        case 'discrete':
          return '遥信/discrete';
        default:
          return '其他/'+serviceId;
      }
    },
    
    // 格式化JSON数据显示
    formatJsonData(jsonData) {
      try {
        if (typeof jsonData === 'string') {
          const parsed = JSON.parse(jsonData);
          return JSON.stringify(parsed, null, 2);
        }
        return JSON.stringify(jsonData, null, 2);
      } catch (e) {
        return jsonData;
      }
    },
    
    // 查询设备数据（分页）
    async searchDeviceData() {
      if (!this.searchDeviceId.trim() && this.currentFilter === 'all') {
        // 如果是全部筛选且没有输入设备标识，给出提示
        if (this.currentFilter === 'all') {
          uni.showToast({ title: '请输入设备标识/Please enter device ID', icon: 'none' });
          return;
        }
      }
      
      if (this.loading) return;
      
      this.loading = true;
      uni.showLoading({ title: '查询中.../Querying...' });
      
      try {
        const res = await new Promise((resolve, reject) => {
          uni.request({
            url: `${config.baseURL}/api/device/query/page`,
            method: 'GET',
            data: {
              deviceIdentifier: this.searchDeviceId,
              serviceId: this.getServiceIdByFilter(),
              page: this.currentPage,
              size: this.pageSize
            },
            header: {
              'Content-Type': 'application/json'
            },
            success: (result) => resolve(result),
            fail: (error) => reject(error)
          });
        });
        
        if (res && res.data && res.data.code === 0) {
          this.searchResults = res.data.data.records || [];
          this.total = res.data.data.total || 0;
          this.totalPages = Math.ceil(this.total / this.pageSize);
          this.searchPerformed = true;
        } else {
          uni.showToast({ title: res.data?.msg || '查询失败/Query failed', icon: 'none' });
          this.searchResults = [];
          this.total = 0;
          this.totalPages = 0;
          this.searchPerformed = true;
        }
      } catch (error) {
        console.error('查询失败', error);
        uni.showToast({ title: '网络错误，请稍后重试/Network error, please try again', icon: 'none' });
        this.searchResults = [];
        this.total = 0;
        this.totalPages = 0;
        this.searchPerformed = true;
      } finally {
        this.loading = false;
        uni.hideLoading();
      }
    },
    
    // 根据筛选条件获取serviceId
    getServiceIdByFilter() {
      switch(this.currentFilter) {
        case 'analog':
          return 'analog';
        case 'discrete':
          return 'discrete';
        case 'other':
          return 'other';
        default:
          return ''; // 全部
      }
    },
    
    // 跳转到指定页
    goToPage(page) {
      if (page < 1 || page > this.totalPages) return;
      if (page === this.currentPage) return;
      
      this.currentPage = page;
      this.searchDeviceData();
    },
    
    // 判断设备是否在线（1小时内）
    isDeviceOnline(updateTime) {
      if (!updateTime) return false;
      
      const updateDate = new Date(updateTime);
      const now = new Date();
      const diffMinutes = (now - updateDate) / (1000 * 60);
      
      return diffMinutes <= 60;
    },
    
    // 格式化日期时间
    formatDateTime(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN');
    },
    
    // 显示详情
    showDetail(item) {
      this.currentDetailData = item.bodyData || '{}';
      this.showDetailModal = true;
    },
  }
};
</script>

<style scoped>
.device-query-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 0;
  box-sizing: border-box;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #2980ff;
  color: #fff;
  height: 88rpx;
}

.header-left {
  flex: 1;
}

.back-btn {
  font-size: 40rpx;
  font-weight: bold;
}

.header-center {
  flex: 2;
  text-align: center;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
}

.header-right {
  flex: 1;
}

.search-section {
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.search-container {
  display: flex;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.search-input {
  flex: 1;
  height: 80rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.search-btn {
  width: 150rpx;
  height: 80rpx;
  background-color: #2980ff;
  color: #fff;
  border-radius: 10rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 筛选样式 */
.filter-section {
  display: flex;
  gap: 20rpx;
}

.filter-item {
  flex: 1;
  text-align: center;
  padding: 15rpx 0;
  border: 2rpx solid #e0e0e0;
  border-radius: 10rpx;
  font-size: 24rpx;
  color: #666;
}

.filter-item.active {
  background-color: #2980ff;
  color: #fff;
  border-color: #2980ff;
}

.result-section {
  flex: 1;
  overflow: hidden;
  padding: 0 30rpx;
}

.result-scroll {
  height: calc(100vh - 420rpx);
}

.result-list {
  padding-right: 10rpx;
}

.result-item {
  padding: 25rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 15rpx;
  margin-bottom: 20rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
}

.result-item:last-child {
  margin-bottom: 0;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.device-id {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  word-break: break-all;
  margin-right: 20rpx;
}

.status-tag {
  padding: 5rpx 15rpx;
  border-radius: 10rpx;
  font-size: 22rpx;
  font-weight: bold;
  white-space: nowrap;
}

.status-tag.online {
  background-color: #e8f5e9;
  color: #4caf50;
}

.status-tag.offline {
  background-color: #ffebee;
  color: #f44336;
}

.item-content {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.service-id, .update-time {
  font-size: 24rpx;
  color: #666;
}

.no-data {
  text-align: center;
  color: #999;
  font-size: 28rpx;
  padding: 50rpx 0;
}

.loading-text {
  text-align: center;
  color: #999;
  font-size: 26rpx;
  padding: 20rpx 0;
}

/* 分页控件样式 */
.pagination-section {
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-top: 2rpx solid #e0e0e0;
}

.pagination-info {
  text-align: center;
  color: #666;
  font-size: 24rpx;
  margin-bottom: 20rpx;
  line-height: 1.5;
}

.pagination-controls {
  display: flex;
  justify-content: center;
  gap: 30rpx;
}

.page-btn {
  padding: 15rpx 30rpx;
  background-color: #2980ff;
  color: #fff;
  border-radius: 10rpx;
  font-size: 26rpx;
  border: none;
  white-space: nowrap;
}

.page-btn:disabled {
  background-color: #c9d8e9;
  color: #fff;
}

/* 详情弹窗样式 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.modal-content {
  width: 95%;
  max-width: 700rpx;
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  max-height: 85vh;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 30rpx;
  background-color: #2980ff;
  color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
}

.modal-close {
  font-size: 48rpx;
  font-weight: normal;
  padding: 10rpx;
  line-height: 1;
}

.modal-body {
  padding: 0;
  flex: 1;
  overflow: hidden;
}

.detail-scroll {
  height: 500rpx;
  padding: 20rpx;
}

.detail-text {
  font-family: 'Courier New', monospace;
  font-size: 22rpx;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-all;
  word-wrap: break-word;
}
</style>
